//https://leetcode.cn/problems/unique-paths-ii/
package codeRandomThoughts.Test63不同路径II;

public class Solution2 {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int m = obstacleGrid.length;
        int n = obstacleGrid[0].length;
        //dp[i][j]:走到(i,j)有dp[i][j]条路径
        int[][] dp = new int[m][n];

        //初始化
        for (int i = 0; i < m && obstacleGrid[i][0] == 0; i++) {
            dp[i][0] = 1;
        }
        for (int j = 0; j < n && obstacleGrid[0][j] == 0; j++) {
            dp[0][j] = 1;
        }

        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                int left = 0;
                int right = 0;

                if (obstacleGrid[i][j - 1] != 1) left = dp[i][j - 1];
                if (obstacleGrid[i - 1][j] != 1) right = dp[i - 1][j];
                if (obstacleGrid[i][j] != 1) dp[i][j] = left + right;
            }
        }

        return dp[m - 1][n - 1];
    }
}
